package com.we.wfc.system.controller;


import com.google.common.collect.Lists;
import com.we.wfc.common.base.Pagination;
import com.we.wfc.common.pojo.ResultPoJo;
import com.we.wfc.system.dto.AreaQueryDto;
import com.we.wfc.system.dto.AreaSaveDto;
import com.we.wfc.system.entity.Area;
import com.we.wfc.system.service.AreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 行政区划表 前端控制器
 * </p>
 *
 * @author zhangby
 * @since 2020-01-04
 */
@RestController
@RequestMapping("/area")
@Api(tags = "行政区划管理")
public class AreaController {

    @Autowired
    private AreaService areaService;

    /**
     * 分页查询
     *
     * @return
     */
    @GetMapping("")
    @ApiOperation(value = "分页查询", notes = "分页查询", produces = "application/json")
    public ResultPoJo<Page<Area>> getAreaList4Page(Pagination pagination, AreaQueryDto areaQueryDto) {

        Page<Area> page = areaService.findAll(
                areaQueryDto.buildQuery(),
                pagination.pageRequest(
                        Sort.by(Sort.Direction.DESC, "createDate")
                )
        );
        return ResultPoJo.ok(page);
    }

    /**
     * 获取地区详情
     *
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "获取地区详情", notes = "获取地区详情", produces = "application/json")
    public ResultPoJo<Area> getAreaById(@PathVariable String id) {
        Area area = areaService.findById(id);
        return ResultPoJo.ok(area);
    }

    /**
     * 行政区划保存
     *
     * @return
     */
    @PostMapping("")
    @ApiOperation(value = "行政区划保存", notes = "行政区划保存", produces = "application/json")
    public ResultPoJo saveArea(@RequestBody AreaSaveDto areaSaveDto) {
        //查询上级的id
        Area parentArea = areaService.findById(areaSaveDto.getParentId());
        Area area = areaSaveDto.convert(parentArea);
        areaService.save(area);
        return ResultPoJo.ok();
    }

    /**
     * 行政区划更新
     *
     * @return
     */
    @PutMapping("/{id}")
    @ApiOperation(value = "行政区划更新", notes = "行政区划更新", produces = "application/json")
    public ResultPoJo updateArea(@PathVariable String id, @RequestBody AreaSaveDto areaSaveDto) {
        //查询上级的id
        Area parentArea = areaService.findById(areaSaveDto.getParentId());
        Area area = (Area) areaSaveDto.convert(parentArea).setId(id);
        areaService.save(area);
        return ResultPoJo.ok();
    }

    /**
     * 删除行政区划
     *
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除行政区划", notes = "删除行政区划", produces = "application/json")
    public ResultPoJo deleteArea(@PathVariable String id) {
        areaService.deleteById4LogicInBatch(Lists.newArrayList(id.split(",")));
        return ResultPoJo.ok();
    }
}

